<template>
  <div class="code-container">
    <pre v-hljs><code :id="codeId" :class="codeLanguage">{{ code }}</code></pre>
    <button class="copy-button" @click="copyCode">复制</button>
  </div>
</template>

<script>
  import MarkdownIt from 'markdown-it';
  import { ElMessage } from 'element-plus';
  export default {
    data() {
      return {
        codeId: 'js-code',
        codeLanguage: 'javascript',
        code: `
function add(x, y) {
  return x + y;
}
`,
      };
    },
    methods: {
      copyCode() {
        const codeEl = document.getElementById(this.codeId);
        const codeContent = codeEl.innerText;
        navigator.clipboard
          .writeText(codeContent)
          .then(() => {
            ElMessage.success('代码已复制');
          })
          .catch(() => {
            ElMessage.warning('复制失败');
          });
      },
    },
    mounted() {
      // 初始化 markdown-it
      const md = new MarkdownIt();
      // 启用 highlight.js 的代码高亮
      console.log(md, 'md');
      md.options.highlight = (code, lang) => {
        console.log(lang, code);
      };

      // 解析 Markdown 文本为 HTML，并渲染到组件中
      const markdownText = `
# My Markdown Editor

\`\`\`javascript
function add(x, y) {
  return x + y;
}
\`\`\`
`;
      this.code = md.render(markdownText);
    },
  };
</script>

<style>
  .code-container {
    position: relative;
  }

  pre {
    border-radius: 3px;
    padding: 10px;
    background-color: #f2f2f2;
  }

  pre code {
    display: block;
    overflow: auto;
    font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
  }

  .copy-button {
    position: absolute;
    top: 5px;
    right: 5px;
    padding: 5px;
    cursor: pointer;
  }
</style>
